package com.cx.mvc.practise.parse;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import com.cx.mvc.practise.parse.vo.XmlActionBean;
import com.cx.mvc.practise.parse.vo.XmlBean;
import com.cx.mvc.practise.parse.vo.XmlFormBean;

public class XmlParser {

	public static Map<String, XmlBean> parseMyStrutsXml(String myStrutsPath)
	{
		Map<String, XmlBean> map = new HashMap<String, XmlBean>();
		SAXBuilder builder=new SAXBuilder();
		try {
			Document document = builder.build(new File(myStrutsPath));
			Element rootElement = document.getRootElement();
			List<Element> formBeansElement = rootElement.getChild("form-beans").getChildren("form-bean");
			for(Element element : formBeansElement)
			{
				XmlBean xmlBean = new XmlBean();
				XmlFormBean xmlFormBean = new XmlFormBean();
				xmlFormBean.setName(element.getAttributeValue("name").trim());
				xmlFormBean.setClassName(element.getAttributeValue("class").trim());
				xmlBean.setXmlFormBean(xmlFormBean);
				map.put(xmlFormBean.getName().trim(), xmlBean);
			}
			List<Element> actionMappingsElement = rootElement.getChild("action-mappings").getChildren("action");
			for(Element element : actionMappingsElement)
			{
				XmlActionBean xmlActionBean = new XmlActionBean();
				xmlActionBean.setName(element.getAttributeValue("name").trim());
				xmlActionBean.setClassName(element.getAttributeValue("type").trim());
				xmlActionBean.setPath(element.getAttributeValue("path").trim());
				List<Element> forwordElements = element.getChildren();
				Map<String, String> forword = new HashMap<String, String>();
				for(Element forwordElement : forwordElements)
				{
					forword.put(forwordElement.getAttribute("name").getValue().trim(), forwordElement.getAttribute("value").getValue().trim());
				}
				xmlActionBean.setForword(forword);
				XmlBean xmlbean = map.remove(xmlActionBean.getName());
				xmlbean.setXmlActionBean(xmlActionBean);
				map.put(xmlActionBean.getPath(), xmlbean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(map);
		return map;
	}
	
	public static void main(String[] args)
	{
		parseMyStrutsXml("src/main/resources/my-struts.xml");
	}
}
